-- BossSceneManager.lua
-- Boss关卡管理器：当角色走到02_03缺口下方时触发进入，Boss房为死胡同

local BossSceneManager = {}
BossSceneManager.__index = BossSceneManager

-- 导入必要模块
local Size = require("Size")
local Color = require("Color")

function BossSceneManager.new()
    local instance = {
        -- 场景配置
        sceneId = "BossScene",
        displayName = "BOSS关卡",
        
        -- Boss房配置
        bossRoomImagePath = "Image/bossroom/bossroom.png",
        bossRoomWidth = 2844,     -- 逻辑宽度
        bossRoomHeight = 1600,    -- 逻辑高度
        
        -- 场景参数
        levelWidth = 2844,         -- 逻辑宽度 2844像素
        levelHeight = 1600,        -- 逻辑高度 1600像素
        floorWidth = 2000,         -- 地板贴图宽度
        floorHeight = 50,          -- 地板贴图高度
        
        -- 场景节点
        sceneNode = nil,
        bossRoomNode = nil,
        floorLayer = nil,
        
        -- 玩家
        playerNode = nil,
        sceneManager = nil,
        
        -- 地面参数
        groundY = 320,                 -- 地面高度
        groundHeight = 50,             -- 地面厚度
        
        -- 状态
        isInitialized = false,
        debugMode = true,
        
        -- 地板管理
        floorTiles = {},
        
        -- 场景边界（Boss房为死胡同，不需要退出）
        sceneBounds = {
            left = 0,
            right = 2844,
            top = 1600,
            bottom = 0,
            width = 2844,
            height = 1600
        },
        
        -- 地面平台（用于碰撞检测）
        groundPlatforms = {},
        
        -- Boss相关（可以后续扩展）
        bossEntity = nil,
        bossSpawned = false
    }
    
    return setmetatable(instance, BossSceneManager)
end

-- 初始化Boss场景
function BossSceneManager:initialize(sceneNode, playerNode, sceneManager, triggerPosition)
    print("====================================")
    print("初始化BOSS关卡场景管理器")
    print("====================================")
    
    if not sceneNode then
        print("错误：场景节点为空")
        return false
    end
    
    self.sceneNode = sceneNode
    self.playerNode = playerNode
    self.sceneManager = sceneManager
    
    -- 设置触发器位置（从主关卡传入）
    if triggerPosition then
        print(string.format("Boss房触发位置: (%.1f, %.1f)", 
            triggerPosition.x, triggerPosition.y))
    end
    
    -- 创建Boss房间
    self:createBossRoom()
    
    -- 创建地板
    self:createFloor()
    
    -- 创建地面碰撞平台
    self:createGroundPlatforms()
    
    -- 设置玩家起始位置（从左侧进入）
    self:setPlayerStartPosition()
    
    self.isInitialized = true
    
    print("BOSS关卡场景初始化完成")
    print(string.format("场景尺寸: %d×%d", self.levelWidth, self.levelHeight))
    print(string.format("Boss房图片: %s", self.bossRoomImagePath))
    print("注意：Boss房为死胡同，玩家无法离开")
    
    return true
end

-- 创建Boss房间
function BossSceneManager:createBossRoom()
    if not self.sceneNode then return end
    
    local Sprite = require("Sprite")
    local Node = require("Node")
    local Vec2 = require("Vec2")
    local Cache = require("Cache")
    local Size = require("Size")
    local Color = require("Color")
    
    -- 创建Boss房间容器
    self.bossRoomNode = Node()
    self.bossRoomNode.position = Vec2(self.levelWidth / 2, self.levelHeight / 2)
    
    -- 加载Boss房间纹理
    local bossRoomTexture = nil
    if Cache:load(self.bossRoomImagePath) then
        local Texture2D = require("Texture2D")
        bossRoomTexture = Texture2D(self.bossRoomImagePath)
    end
    
    if bossRoomTexture then
        -- 创建Boss房间精灵
        local bossRoomSprite = Sprite(bossRoomTexture)
        if bossRoomSprite then
            -- 缩放以匹配逻辑大小
            local scaleX = self.levelWidth / bossRoomSprite.width
            local scaleY = self.levelHeight / bossRoomSprite.height
            bossRoomSprite.scaleX = scaleX
            bossRoomSprite.scaleY = scaleY
            
            self.bossRoomNode:addChild(bossRoomSprite)
            
            print(string.format("Boss房图片加载成功: 原始尺寸(%d×%d), 缩放(%.2f×%.2f)", 
                bossRoomSprite.width, bossRoomSprite.height, scaleX, scaleY))
        end
    else
        -- 创建备用Boss房间
        self.bossRoomNode.size = Size(self.levelWidth, self.levelHeight)
        self.bossRoomNode.color = Color(0.1, 0.1, 0.1, 1)  -- 暗色背景
        
        -- 添加Boss房装饰
        self:createBossRoomDecoration()
        
        print("使用备用Boss房背景")
    end
    
    -- 添加到场景
    self.sceneNode:addChild(self.bossRoomNode, -100)
end

-- 创建Boss房间装饰（备用背景时使用）
function BossSceneManager:createBossRoomDecoration()
    local Node = require("Node")
    local Vec2 = require("Vec2")
    local Size = require("Size")
    local Color = require("Color")
    
    -- 创建Boss房标志
    local bossSymbol = Node()
    bossSymbol.size = Size(200, 200)
    bossSymbol.position = Vec2(self.levelWidth / 2, self.levelHeight * 0.7)
    bossSymbol.color = Color(0.8, 0.1, 0.1, 1)  -- 红色
    
    self.bossRoomNode:addChild(bossSymbol)
    
    -- 创建火焰效果
    for i = 1, 5 do
        local torch = Node()
        local torchX = 500 + (i - 1) * 400
        local torchY = self.groundY + 200
        torch.size = Size(60, 180)
        torch.position = Vec2(torchX, torchY)
        torch.color = Color(1, 0.5, 0, 0.8)  -- 火焰色
        
        self.bossRoomNode:addChild(torch)
    end
end

-- 创建地板
function BossSceneManager:createFloor()
    if not self.sceneNode then return end
    
    local Node = require("Node")
    local Vec2 = require("Vec2")
    local Size = require("Size")
    local Color = require("Color")
    
    -- 创建地板层容器
    self.floorLayer = Node()
    self.floorLayer.position = Vec2(0, self.groundY)
    
    -- 计算需要的地板切片数量
    local tileCount = math.ceil(self.levelWidth / self.floorWidth)
    
    for i = 1, tileCount do
        local tileNode = Node()
        local tileX = (i - 1) * self.floorWidth
        
        -- 创建Boss房专用地板（深色）
        tileNode.size = Size(self.floorWidth, self.groundHeight)
        local darkValue = 0.1 + (i % 2) * 0.05
        tileNode.color = Color(darkValue, darkValue, darkValue, 1)
        
        tileNode.position = Vec2(tileX, 0)
        self.floorLayer:addChild(tileNode)
        
        table.insert(self.floorTiles, {
            node = tileNode,
            index = i,
            position = tileX
        })
    end
    
    -- 添加到场景
    self.sceneNode:addChild(self.floorLayer, -50)
    
    print(string.format("Boss房地板创建完成: %d 个切片", tileCount))
end

-- 创建地面碰撞平台
function BossSceneManager:createGroundPlatforms()
    print("创建BOSS房地面碰撞平台...")
    
    self.groundPlatforms = {}
    
    -- 创建连续的地面平台（整个Boss房宽度）
    local groundPlatform = {
        x = 0,
        y = self.groundY,
        width = self.levelWidth,
        height = self.groundHeight,
        isWalkable = true,
        type = "boss_ground"
    }
    
    table.insert(self.groundPlatforms, groundPlatform)
    
    -- 在Boss房右侧添加墙壁（阻止玩家离开）
    local rightWall = {
        x = self.levelWidth - 50,  -- 离右侧50像素
        y = self.groundY,
        width = 100,  -- 墙壁厚度
        height = 800, -- 墙壁高度
        isWalkable = false,
        type = "boss_wall"
    }
    
    table.insert(self.groundPlatforms, rightWall)
    
    print("Boss房地面碰撞平台创建完成（包含右侧阻挡墙壁）")
end

-- 设置玩家起始位置
function BossSceneManager:setPlayerStartPosition()
    -- 玩家从左侧进入Boss房
    self.playerStartPosition = {
        x = 100,                    -- 从左侧100像素处进入
        y = self.groundY + 150      -- 在地面之上150像素
    }
end

-- 更新场景（每帧调用）
function BossSceneManager:update(dt, playerX, playerY)
    if not self.isInitialized or not self.playerNode then return end
    
    -- Boss房为死胡同，不需要检查退出条件
    -- 可以在这里添加Boss逻辑
    
    return true
end

-- 获取玩家起始位置
function BossSceneManager:getPlayerStartPosition()
    return self.playerStartPosition
end

-- 获取地面平台（用于碰撞检测）
function BossSceneManager:getGroundPlatforms()
    return self.groundPlatforms
end

-- 检查位置是否可行走
function BossSceneManager:isWalkable(x, y, characterRadius)
    characterRadius = characterRadius or 25
    
    for _, platform in ipairs(self.groundPlatforms) do
        -- 检查水平对齐
        if x >= platform.x - characterRadius and x <= platform.x + platform.width + characterRadius then
            local platformTop = platform.y + platform.height
            local characterBottom = y - characterRadius
            
            -- 检查垂直距离
            if characterBottom >= platformTop - 30 and characterBottom <= platformTop + 10 then
                return platform.isWalkable  -- 如果是墙壁，返回false
            end
        end
    end
    
    return false
end

-- 获取应站立的地面
function BossSceneManager:getStandingPlatform(x, y, characterRadius)
    characterRadius = characterRadius or 25
    local characterBottom = y - characterRadius
    
    for _, platform in ipairs(self.groundPlatforms) do
        -- 检查水平对齐
        if x >= platform.x - characterRadius and x <= platform.x + platform.width + characterRadius then
            local platformTop = platform.y + platform.height
            
            -- 检查垂直距离
            if characterBottom >= platformTop - 30 and characterBottom <= platformTop + 5 then
                if platform.isWalkable then
                    return {
                        type = platform.type,
                        x = platform.x,
                        y = platformTop,
                        width = platform.width,
                        height = platform.height,
                        isSlope = false
                    }
                end
            end
        end
    end
    
    return nil
end

-- 获取场景边界
function BossSceneManager:getSceneBounds()
    return self.sceneBounds
end

-- 清理资源
function BossSceneManager:cleanup()
    print("清理BOSS关卡资源...")
    
    if self.floorLayer and self.floorLayer.parent then
        self.floorLayer:removeFromParent()
    end
    
    if self.bossRoomNode and self.bossRoomNode.parent then
        self.bossRoomNode:removeFromParent()
    end
    
    self.floorTiles = {}
    self.groundPlatforms = {}
    self.floorLayer = nil
    self.bossRoomNode = nil
    self.sceneNode = nil
    self.playerNode = nil
    self.sceneManager = nil
    self.isInitialized = false
    self.bossSpawned = false
    self.bossEntity = nil
    
    print("BOSS关卡资源清理完成")
end

-- 在BossSceneManager类中添加：

-- 生成Boss
function BossSceneManager:spawnBoss()
    if self.bossSpawned then return end
    
    print("====================================")
    print("生成BOSS - 腐化守卫")
    print("====================================")
    
    -- Boss生成位置（房间中央）
    local bossX = self.levelWidth / 2
    local bossY = self.groundY + 400
    
    -- 创建Boss节点
    local Node = require("Node")
    local bossNode = Node()
    bossNode.x = bossX
    bossNode.y = bossY
    
    -- 添加到场景
    self.sceneNode:addChild(bossNode)
    
    -- 创建Boss实体数据
    self.bossEntity = {
        id = "boss_corrupted_guard",
        type = "boss",
        position = {x = bossX, y = bossY},
        health = 500,
        maxHealth = 500,
        isAlive = true,
        node = bossNode,
        scale = 0.2,
        radius = 40,
        attackRange = 200,
        moveSpeed = 180,
        isAngry = false,  -- 第二阶段狂暴状态
        phase = 1         -- 当前阶段
    }
    
    -- 创建Boss Spine动画
    local Spine = require("Spine")
    local bossSpine = Spine("model/boss/boss")
    if bossSpine then
        bossSpine.scaleX = self.bossEntity.scale
        bossSpine.scaleY = self.bossEntity.scale
        bossSpine:play("walk", true)
        bossNode:addChild(bossSpine)
        self.bossEntity.spineNode = bossSpine
    else
        print("警告：Boss Spine动画加载失败，使用占位符")
        -- 创建占位符
        local placeholder = Node()
        placeholder.size = require("Size")(100, 150)
        placeholder.color = require("Color")(0.8, 0.1, 0.1, 1)
        bossNode:addChild(placeholder)
    end
    
    -- 创建Boss血条
    self:createBossHealthBar()
    
    -- 设置Boss AI
    self:setupBossAI()
    
    self.bossSpawned = true
    
    print(string.format("Boss生成完成: 位置(%.1f,%.1f), 血量=%d/%d",
        bossX, bossY, self.bossEntity.health, self.bossEntity.maxHealth))
    
    return self.bossEntity
end

-- 创建Boss血条
function BossSceneManager:createBossHealthBar()
    local HealthBar = require("HealthBar")
    
    self.bossHealthBar = HealthBar.new({
        width = 300,
        height = 30,
        currentHealth = self.bossEntity.health,
        maxHealth = self.bossEntity.maxHealth,
        showText = true
    })
    
    if self.bossHealthBar then
        local uiNode = self.bossHealthBar:create()
        if uiNode then
            -- 将血条放在屏幕顶部
            uiNode.x = self.levelWidth / 2
            uiNode.y = self.levelHeight - 50
            self.sceneNode:addChild(uiNode)
            
            print("Boss血条创建成功")
        end
    end
end

-- 设置Boss AI
function BossSceneManager:setupBossAI()
    if not self.bossEntity then return end
    
    -- Boss AI状态
    self.bossAI = {
        state = "idle",  -- idle, patrol, chase, attack
        lastAttackTime = 0,
        attackCooldown = 2.0,
        attackPattern = 1,  -- 攻击模式
        moveDirection = 1,
        patrolTimer = 0,
        maxPatrolTime = 3.0,
        isCharging = false,
        chargeCooldown = 0
    }
end

-- 更新Boss
function BossSceneManager:updateBoss(dt, playerX, playerY)
    if not self.bossEntity or not self.bossEntity.isAlive then return end
    
    -- 检查位置是否低于-500
    if self.bossEntity.position.y < -500 then
        print("Boss掉出世界，死亡")
        self.bossEntity.isAlive = false
        self:onBossDefeated()
        return
    end
    
    -- 更新Boss AI
    self:updateBossAI(dt, playerX, playerY)
    
    -- 更新Boss血条
    if self.bossHealthBar then
        self.bossHealthBar:updateHealth(self.bossEntity.health, self.bossEntity.maxHealth)
        
        -- 检查Boss是否死亡
        if self.bossEntity.health <= 0 and self.bossEntity.isAlive then
            self.bossEntity.isAlive = false
            self:onBossDefeated()
        end
    end
end

-- 更新Boss AI
function BossSceneManager:updateBossAI(dt, playerX, playerY)
    if not self.bossAI then return end
    
    local boss = self.bossEntity
    local ai = self.bossAI
    
    -- 计算到玩家的距离
    local distanceX = math.abs(playerX - boss.position.x)
    local distanceY = math.abs(playerY - boss.position.y)
    local distance = math.sqrt(distanceX^2 + distanceY^2)
    
    -- AI状态机
    if ai.state == "idle" then
        -- 空闲状态：等待玩家接近
        if distance < 800 then
            ai.state = "chase"
            print("Boss发现玩家，开始追击")
        else
            -- 巡逻
            ai.patrolTimer = ai.patrolTimer + dt
            if ai.patrolTimer > ai.maxPatrolTime then
                ai.moveDirection = -ai.moveDirection
                ai.patrolTimer = 0
            end
            
            -- 移动Boss
            boss.position.x = boss.position.x + ai.moveDirection * boss.moveSpeed * dt * 0.3
        end
        
    elseif ai.state == "chase" then
        -- 追击玩家
        if distance > 1000 then
            ai.state = "idle"
            print("Boss丢失目标，返回空闲")
            return
        end
        
        -- 向玩家移动
        local direction = playerX > boss.position.x and 1 or -1
        boss.position.x = boss.position.x + direction * boss.moveSpeed * dt * 0.5
        
        -- 更新面向方向
        if boss.spineNode then
            boss.spineNode.fliped = direction > 0
        end
        
        -- 检查是否在攻击范围内
        if distanceX < boss.attackRange and distanceY < 100 then
            ai.state = "attack"
        end
        
    elseif ai.state == "attack" then
        -- 攻击状态
        if distanceX > boss.attackRange * 1.2 or distanceY > 150 then
            ai.state = "chase"
            return
        end
        
        -- 攻击冷却
        local currentTime = os.time()
        if currentTime - ai.lastAttackTime > ai.attackCooldown then
            self:performBossAttack()
            ai.lastAttackTime = currentTime
            
            -- 随机选择下一次攻击模式
            ai.attackPattern = math.random(1, 3)
            
            -- 根据血量进入第二阶段
            if boss.health < boss.maxHealth * 0.5 and not boss.isAngry then
                boss.isAngry = true
                ai.attackCooldown = 1.5  -- 狂暴状态攻击更快
                print("Boss进入狂暴状态！")
            end
        end
    end
    
    -- 更新节点位置
    if boss.node then
        boss.node.x = boss.position.x
        boss.node.y = boss.position.y
    end
end

-- 执行Boss攻击
function BossSceneManager:performBossAttack()
    local boss = self.bossEntity
    local ai = self.bossAI
    
    if not boss or not boss.isAlive then return end
    
    -- 根据攻击模式执行不同攻击
    if ai.attackPattern == 1 then
        -- 模式1：下劈
        print("Boss攻击：下劈")
        if boss.spineNode then
            boss.spineNode:play("a1", false)
        end
    elseif ai.attackPattern == 2 then
        -- 模式2：上挑
        print("Boss攻击：上挑")
        if boss.spineNode then
            boss.spineNode:play("a2", false)
        end
    else
        -- 模式3：冲锋
        print("Boss攻击：冲锋")
        if boss.spineNode then
            boss.spineNode:play("dash1", false)
        end
        ai.isCharging = true
        ai.chargeCooldown = 1.0
    end
end

-- Boss被击败
function BossSceneManager:onBossDefeated()
    print("====================================")
    print("BOSS 被击败！")
    print("====================================")
    
    -- 播放死亡动画
    if self.bossEntity.spineNode then
        self.bossEntity.spineNode:play("hurt", false)
    end
    
    -- 移除血条
    if self.bossHealthBar and self.bossHealthBar.uiNode then
        self.bossHealthBar.uiNode:removeFromParent()
    end
    
    -- 可以在这里添加奖励掉落、场景切换等逻辑
end

-- 对Boss应用伤害
function BossSceneManager:applyDamageToBoss(damage)
    if not self.bossEntity or not self.bossEntity.isAlive then
        return false
    end
    
    local oldHealth = self.bossEntity.health
    self.bossEntity.health = math.max(0, self.bossEntity.health - damage)
    
    print(string.format("Boss受到伤害: %d, 血量: %d/%d",
        damage, self.bossEntity.health, self.bossEntity.maxHealth))
    
    -- 播放受伤动画
    if self.bossEntity.spineNode then
        self.bossEntity.spineNode:play("hurt", false)
    end
    
    return self.bossEntity.health <= 0
end



return BossSceneManager